package dom;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseXML {

	private String xmlFilePath = "src/dom/xml/ncc.xml";

	public ParseXML() {

	}

	public ParseXML(String path) {
		this.xmlFilePath = path;
	}

	public List<Encode> parseXML() {
		List<Encode> encodeList = new ArrayList<Encode>();

		File xmlFile = new File(xmlFilePath);
		if (xmlFile.exists() == false) {
			System.out.println("file does not exist.");
			return null;
		}

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		Document document = null;

		try {
			db = dbf.newDocumentBuilder();
			document = db.parse(xmlFile);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Element element = document.getDocumentElement();
		NodeList encodes = element.getElementsByTagName("Encode");
		for (int i = 0; i < encodes.getLength(); i++) {
			Element e = (Element) encodes.item(i);
			Encode encode = new Encode();
			// if the node has attributes, then get it with following method,
			// e.g., <node name"nodeName">
			// String name = e.getAttribute("name");
			NodeList childNodes = e.getChildNodes();
			for (int j = 0; j < childNodes.getLength(); j++) {
				if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {

					if ("Enable".equals(childNodes.item(j).getNodeName())) {
						encode.setEnable(Boolean.parseBoolean(childNodes.item(j).getFirstChild()
								.getNodeValue()));
					}
					if ("Name".equals(childNodes.item(j).getNodeName())) {
						encode.setName(childNodes.item(j).getFirstChild().getNodeValue());
					}
					if ("StreamName".equals(childNodes.item(j).getNodeName())) {
						encode.setStreamName(childNodes.item(j).getFirstChild().getNodeValue());
					}
				}
			}
			encodeList.add(encode);
		}
		return encodeList;
	}

	public static void main(String[] args) {
		ParseXML pXML = new ParseXML();
		List<Encode> list = pXML.parseXML();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).isEnable()) {
				System.out.println(list.get(i).getName() + "--" + list.get(i).getStreamName());
			}
		}
	}
}
